package com.jabo.douban.demo.presentation.viewmodel;

import android.app.Application;
import android.os.CountDownTimer;

import com.jabo.douban.demo.utils.AppInfoUtil;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

/**
 * @anthor JZheng3
 * @Time: 2020/2/27
 */
public class SplashActivityViewModel extends AndroidViewModel {

    private MutableLiveData<String> mAppVersionLiveData;
    private MutableLiveData<Long> mSkipSecondLiveData;
    private CountDownTimer mCountDownTimer;

    public SplashActivityViewModel(@NonNull Application application) {
        super(application);
    }

    public LiveData<String> getAppVersionLiveData() {
        if (mAppVersionLiveData == null) {
            mAppVersionLiveData = new MutableLiveData<>();
            mAppVersionLiveData.setValue(AppInfoUtil.getVersion(getApplication()));
        }
        return mAppVersionLiveData;
    }

    public MutableLiveData<Long> getSkipSecondLiveData() {
        if (mSkipSecondLiveData == null) {
            mSkipSecondLiveData = new MutableLiveData<>();
            mSkipSecondLiveData.setValue(0L);
        }
        return mSkipSecondLiveData;
    }

    public void startSkipTime() {
        if (mCountDownTimer == null) {
            mCountDownTimer = new CountDownTimer(5000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    mSkipSecondLiveData.postValue(millisUntilFinished);
                }

                @Override
                public void onFinish() {
                    mSkipSecondLiveData.postValue(-1L);
                }
            };
        }
        mCountDownTimer.start();
    }

    public void cancleTimer() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        cancleTimer();
    }

}
